import {createStore} from 'vuex'
import {getRequest} from "../api/api";
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import {Notification} from '@arco-design/web-vue';

export const store = createStore({
    state: {
        routes: [],
        sessions: {},
        globalDots: 0,
        dots: {},
        admins: [],
        currentSession: null,
        currentAdmin: null,
        stomp: null
    },
    mutations: {
        initCurrentAdmin(state, admin) {
            state.currentAdmin = admin
        },
        initRoutes(state, data) {
            state.routes = data
        },
        changeCurrentSession(state, session) {
            state.currentSession = session
            if (state.dots[state.currentAdmin.username + '#' + session.username]) {
                state.globalDots -= state.dots[state.currentAdmin.username + '#' + session.username]
            }
            state.dots[state.currentAdmin.username + '#' + session.username] = 0
        },
        addMessage(state, msg) {
            let mss = state.sessions[state.currentAdmin.username + '#' + msg.to]
            if (!mss) {
                state.sessions[state.currentAdmin.username + '#' + msg.to] = []
            }
            if (!state.dots[state.currentAdmin.username + '#' + msg.to]) {
                state.dots[state.currentAdmin.username + '#' + msg.to] = 0
            }
            if (!state.currentSession || state.currentSession.username !== msg.to) {
                state.dots[state.currentAdmin.username + '#' + msg.to] += 1
                state.globalDots += 1
            }
            state.sessions[state.currentAdmin.username + '#' + msg.to].push({
                content: msg.content,
                date: new Date(),
                self: !msg.notSelf
            })
        },
        INIT_ADMINS(state, data) {
            state.admins = data
        },
        INIT_DATA(state) {
            let data = localStorage.getItem('vue-chat-session')
            let dots = localStorage.getItem('vue-chat-dots')
            let globalDots = localStorage.getItem('globalDots')
            if (data) {
                state.sessions = JSON.parse(data)
            }
            if (dots) {
                state.dots = JSON.parse(dots)
            }
            if (globalDots) {
                state.globalDots = parseInt(globalDots)
            }
        }
    },
    actions: {
        connectWS(context) {
            let token = window.localStorage.getItem('token')
            context.state.stomp = null
            let sockjs = new SockJS('http://localhost:8081/wsyeb/ep', null, {timeout: 15000})
            context.state.stomp = Stomp.over(sockjs);
            context.state.stomp.connect({'Auth-Token': token}, success => {
                context.state.stomp.subscribe('/user/queue/chat', msg => {
                    let resMsg = JSON.parse(msg.body)
                    //如果有非当前对话的人发来消息,弹出消息并在对应头像,铃铛图标旁显示红点
                    console.log(context.state.currentSession)
                    if (!context.state.currentSession || resMsg.from !== context.state.currentSession.username) {
                        Notification.info({
                            title: resMsg.fromNickName + ' 发来一条消息',
                            content: resMsg.content.length > 10 ? resMsg.content.substr(0, 10) : resMsg.content
                        })
                    }
                    resMsg.notSelf = true
                    resMsg.to = resMsg.from
                    context.commit('addMessage', resMsg)
                })
            }, error => {
                console.log(error)
            })
        },
        initData(context) {
            getRequest('/chat/').then(res => {
                if (res) {
                    context.state.currentSession = null
                    context.commit('INIT_ADMINS', res.obj)
                    context.commit('INIT_DATA')
                }
            })
        }
    }
})
store.watch(function (state) {
        return state.sessions
    }, function (val) {
        localStorage.setItem('vue-chat-session', JSON.stringify(val))
    },
    {
        deep: true
    }
)
store.watch(function (state) {
        return state.dots
    }, function (val) {
        localStorage.setItem('vue-chat-dots', JSON.stringify(val))
    },
    {
        deep: true
    }
)
store.watch(function (state) {
        return state.globalDots
    }, function (val) {
        localStorage.setItem('globalDots', val)
    },
    {
        deep: true
    }
)
